<script setup lang="ts">
import { h, onMounted, reactive, ref } from 'vue';
import Nifi from '../../nifi';
import { ElSteps, ElStep, ElMessage, ElButton } from "element-plus"
import {t} from "../../i18n/index"

const emits = defineEmits<{ finish: [boolean] }>()
const { nifi, id , data } = defineProps<{ id: string, nifi: Nifi,data:any }>()


const active = ref(0)
const errMsg = ref("")
//

// 停止运行引用服务
const s = reactive<('' | 'wait' | 'success' | "error")[]>(['wait','wait','wait','wait','wait'])

const updateStatus = (d:any) => {
    const ts = d.request.updateSteps;
    for(let i = 0,l = ts.length; i< l; i++){
        const t = ts[i];
        s[i] = t.complete ? 'success' : 'wait'
    }
}

const init = async (id: string, data: any) => {
    let url = `/nifi-api/parameter-contexts/${id}/update-requests`
    let res: any;
    try {
        // 修改请求
        res = await nifi.api.post(url, data)
        //
        url = `/nifi-api/parameter-contexts/${id}/update-requests/${res.request.requestId}`
        //
        updateStatus(res);
        while (!res.request.complete) {
            res = await nifi.api.get(url);
        }
        updateStatus(res);
        //
        url = url + '?disconnectedNodeAcknowledged=false';
        res = await nifi.api.delete(url);
        updateStatus(res);
    } catch (error) {
        ElMessage.error(t('param-step-update-failed',{error}))
        console.error(error);
        errMsg.value = error + '';
        return false;
    }
}



const loadingIcon = h('div', { class: "i-line-md:loading-alt-loop w-1em h-1em" })

onMounted(() => {
    init(id,data)
})

</script>

<template>
    <div class="p-8 backdrop-blur-md relative w-800">
        <el-steps class="w-full" :space="300" :active="active" align-center direction="vertical">
            <el-step :title="t('param-step-1')" :status="s[0]" :icon="s[0] == 'wait' ? loadingIcon : undefined" />
            <el-step :title="t('param-step-2')" :status="s[1]" :icon="s[1] == 'wait' ? loadingIcon : undefined" />
            <el-step :title="t('param-step-3')" :status="s[2]" :icon="s[2] == 'wait' ? loadingIcon : undefined" />
            <el-step :title="t('param-step-4')" :status="s[3]" :icon="s[3] == 'wait' ? loadingIcon : undefined" />
            <el-step :title="t('param-step-5')" :status="s[4]" :icon="s[4] == 'wait' ? loadingIcon : undefined" />
        </el-steps>
        <div v-if="errMsg" class="w-full box-border p-8 rd-8 b-1 b-solid m-y-16 c-#f56c6c b-#f56c6c bg-#fef0f0">
            {{ errMsg }}
        </div>
        <div v-if="errMsg" class="w-full flex justify-center">
            <ElButton type="info" plain @click="emits('finish', true)">{{t('box-close-text')}}</ElButton>
        </div>
    </div>
</template>